import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

// 定义消息类型接口
import type { Message } from '@/views/message/data'

export const useMessageStore = defineStore('message', () => {
    // 活动消息数据
    const allActivityMessages = ref<Message[]>([
        { id: 1, title: '活动通知', subtitle: '恭喜获得20个租币，请查收', date: '2023-06-15 10:30', read: false },
        { id: 2, title: '免费得iPhone11', subtitle: '参与活动有机会赢取iPhone11', date: '2023-06-14 15:45', read: false },
        { id: 3, title: '这里的字符限制是十二个字', subtitle: '活动规则详细说明，请查阅', date: '2023-06-13 09:20', read: true },
        { id: 4, title: '节日赠租币', subtitle: '端午节快乐，赠送50个租币', date: '2023-06-12 14:10', read: false },
        { id: 5, title: '会员日特惠', subtitle: '每月15日会员专享优惠活动', date: '2023-06-11 16:30', read: true },
        { id: 6, title: '新人福利', subtitle: '注册即送100个租币礼包', date: '2023-06-10 11:25', read: false },
        { id: 7, title: '夏日促销', subtitle: '夏日清凉活动，租机享8折', date: '2023-06-09 13:40', read: false },
        { id: 8, title: '限时抢购', subtitle: '每日10点准时开抢特价商品', date: '2023-06-08 08:50', read: true },
        { id: 9, title: '邀请好友', subtitle: '邀请好友注册，双方各得50租币', date: '2023-06-07 14:20', read: false },
        { id: 10, title: '周末活动', subtitle: '周末租机额外赠送20%租币', date: '2023-06-06 10:15', read: true },
        { id: 11, title: '生日礼包', subtitle: '祝您生日快乐，专属礼包已送达', date: '2023-06-05 16:30', read: false },
        { id: 12, title: '抽奖活动', subtitle: '幸运大转盘，100%中奖率', date: '2023-06-04 14:45', read: false },
        { id: 13, title: '积分兑换', subtitle: '积分商城上新，租币兑换好礼', date: '2023-06-03 11:20', read: true },
        { id: 14, title: '评价返现', subtitle: '评价订单返5元现金券', date: '2023-06-02 09:10', read: false },
        { id: 15, title: '限时免押', subtitle: '部分机型限时免押金租赁', date: '2023-06-01 15:30', read: false },
        { id: 16, title: '老用户专享', subtitle: '老用户回归，赠送150租币', date: '2023-05-31 16:45', read: true },
        { id: 17, title: '新品上线', subtitle: '最新款手机已上线，抢先体验', date: '2023-05-30 10:20', read: false },
        { id: 18, title: '优惠券到账', subtitle: '您有3张优惠券已到账，请查收', date: '2023-05-29 14:10', read: false },
        { id: 19, title: '系统升级', subtitle: '系统将于今晚23:00进行升级维护', date: '2023-05-28 17:30', read: true },
        { id: 20, title: '服务优化', subtitle: '租机流程已优化，操作更便捷', date: '2023-05-27 11:45', read: false }
    ])

    // 订单消息数据
    const allOrderMessages = ref<Message[]>([
        { id: 5, title: '订单已取消', subtitle: '订单已成功取消，感谢您的关注', date: '2020-03-23 14:30', read: false }
    ])
    const isCheckedIn = ref(false)
    // 计算是否有未读活动消息
    const hasUnreadActivityMessages = computed(() => {
        return allActivityMessages.value.some(message => !message.read)
    })

    // 计算是否有未读订单消息
    const hasUnreadOrderMessages = computed(() => {
        return allOrderMessages.value.some(message => !message.read)
    })

    // 标记消息为已读
    const markMessageAsRead = (messageId: number, type: 'activity' | 'order'): Message | null => {
        const sourceList = type === 'activity' ? allActivityMessages.value : allOrderMessages.value
        const message = sourceList.find(m => m.id === messageId)

        if (message && !message.read) {
            message.read = true
            saveToLocalStorage()
        }

        return message || null
    }

    // 删除消息
    const deleteMessage = (messageId: number, type: 'activity' | 'order'): boolean => {
        const sourceList = type === 'activity' ? allActivityMessages : allOrderMessages
        const initialLength = sourceList.value.length

        sourceList.value = sourceList.value.filter(m => m.id !== messageId)

        const deleted = sourceList.value.length < initialLength
        if (deleted) {
            saveToLocalStorage()
        }

        return deleted
    }

    // 一键已读
    const markAllAsRead = (type: 'activity' | 'order'): void => {
        const sourceList = type === 'activity' ? allActivityMessages.value : allOrderMessages.value

        sourceList.forEach(message => {
            message.read = true
        })

        saveToLocalStorage()
    }

    // 删除所有已读
    const deleteAllRead = (type: 'activity' | 'order'): void => {
        const sourceList = type === 'activity' ? allActivityMessages : allOrderMessages

        sourceList.value = sourceList.value.filter(m => !m.read)

        saveToLocalStorage()
    }

    // 保存到本地存储
    const saveToLocalStorage = () => {
        localStorage.setItem('activityMessages', JSON.stringify(allActivityMessages.value))
        localStorage.setItem('orderMessages', JSON.stringify(allOrderMessages.value))
    }

    // 从本地存储加载
    const loadFromLocalStorage = () => {
        try {
            const savedActivityMessages = localStorage.getItem('activityMessages')
            if (savedActivityMessages) {
                const parsed = JSON.parse(savedActivityMessages)
                if (Array.isArray(parsed)) {
                    allActivityMessages.value = parsed
                }
            }

            const savedOrderMessages = localStorage.getItem('orderMessages')
            if (savedOrderMessages) {
                const parsed = JSON.parse(savedOrderMessages)
                if (Array.isArray(parsed)) {
                    allOrderMessages.value = parsed
                }
            }
        } catch (error) {
            console.error('Failed to load messages from localStorage:', error)
        }
    }

    // 添加新消息
    const addMessage = (message: Omit<Message, 'id'>, type: 'activity' | 'order'): Message => {
        const sourceList = type === 'activity' ? allActivityMessages : allOrderMessages
        const newId = sourceList.value.length > 0 ? Math.max(...sourceList.value.map(m => m.id)) + 1 : 1
        const newMessage = { ...message, id: newId }

        sourceList.value.unshift(newMessage) // 添加到列表开头
        saveToLocalStorage()

        return newMessage
    }

    // 初始化时加载数据
    loadFromLocalStorage()

    return {
        // 数据
        allActivityMessages,
        allOrderMessages,
        isCheckedIn,
        // 计算属性
        hasUnreadActivityMessages,
        hasUnreadOrderMessages,

        // 方法
        markMessageAsRead,
        deleteMessage,
        markAllAsRead,
        deleteAllRead,
        addMessage,
        loadFromLocalStorage
    }
})